package bb.lanxing.common.engin;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import com.blankj.utilcode.util.UriUtils;
import com.google.gson.GsonBuilder;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.sport.SportRecordDetailActivity;
import bb.lanxing.chat.utils.IntentUtils;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.common.engin.util.EnginUtil;
import bb.lanxing.common.engin.util.SettingUtils;
import bb.lanxing.lib.devices.utils.AntPlusUtils;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.Workout;
import bb.lanxing.model.database.WorkoutOther;
import bb.lanxing.mvp.model.RouteInfoModelImpl;
import bb.lanxing.mvp.model.SprintNavModelImpl;
import bb.lanxing.model.json.Route;
import bb.lanxing.test.WorkoutTest;
import bb.lanxing.util.AppFileUtils;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class DeveloperOptionsActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    private static final String TAG = "DeveloperOptionsActivity";
    ArrayAdapter<String> adapter;
    private ListView listView;
    private Toolbar toolbar;
    private boolean needRestart = false;
    private final int EXPORT_SETTINGS = 0;
    private final int IMPORT_SETTINGS = 1;
    private final int SERVER_CONFIG = 2;
    private final int LOCATION_SIMULATE = 3;
    private final int LOCATION_RECODER = 4;
    private final int ANT_PLUS = 5;
    private final int DUMP_LOG = 6;
    private final int LOG = 7;
    private final int FIRMWARE_UPDATE_TEST = 8;
    private final int WORKOUT_FILE_SIMULATE = 9;
    private final int WORKOUT_SIMULATE = 10;
    private final int WORKOUT_MERGE = 11;
    private final int FIT_IMPORT = 12;
    private final int WORKOUT_DETAIL = 13;
    private final int WEB_VIEW = 14;
    private final int ROUTE_BOOK_TO_SPRINT_NAV = 15;
    private final int LOCALTION_SIMULATE_FILE_BUILD = 16;
    private final int LOCALTION_SIMULATE_FILE_BUILD_FOR_FIT = 17;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.engin_activity);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        setTitle("开发者模式");
        this.listView.setAdapter(getFunctionAdapter());
        this.listView.setOnItemClickListener(this);
        MobclickAgent.onEventValue(App.getContext(), UmengEventConst.ENGINE_MODE_ENTER, null, 1);
    }

    private ListAdapter getFunctionAdapter() {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        this.adapter = arrayAdapter;
        updateListItem(arrayAdapter);
        return this.adapter;
    }

    private void updateListItem(ArrayAdapter<String> arrayAdapter) {
        arrayAdapter.clear();
        arrayAdapter.add("导出设置");
        arrayAdapter.add("导入设置");
        arrayAdapter.add("服务器配置");
        arrayAdapter.add(EnginUtil.isSimulateLocation() ? "关闭位置模拟" : "开启位置模拟");
        arrayAdapter.add(EnginUtil.isRecordOpen() ? "关闭轨迹记录" : "开启轨迹记录");
        arrayAdapter.add(SharedManager.getInstance().getBoolean(SharedManager.KEY_ANT_PLUS_IS_ENABLED, false) ? "关闭ANT+" : "打开ANT+");
        arrayAdapter.add("结束运动后导出日志");
        if (EnginUtil.isAPKDebugable(this)) {
            arrayAdapter.add(SharedManager.getInstance().getBoolean("debugMode", App.getContext().isDebugMode()) ? "关闭Log输出" : "打开Log输出");
            arrayAdapter.add("固件升级测试");
            arrayAdapter.add("轨迹模拟");
            arrayAdapter.add("轨迹文件模拟");
            arrayAdapter.add("轨迹合并");
            arrayAdapter.add("Fit文件导入测试");
            arrayAdapter.add("查看TA人轨迹");
            arrayAdapter.add("WebView测试");
            arrayAdapter.add("路书转SPRINT导航文件");
            arrayAdapter.add("生成位置模拟文件");
            arrayAdapter.add("使用FIT生成位置模拟文件");
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) {
        if (menuItem.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(menuItem);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
        String str;
        switch (i) {
            case EXPORT_SETTINGS:
                String enginDir = EnginUtil.getEnginDir();
                if (SettingUtils.writeSetting(enginDir)) {
                    Toast.makeText(this, "Save succeed ! The file stored at " + enginDir + File.separator + SettingUtils.SETTING_FILE_NAME, Toast.LENGTH_LONG).show();
                    return;
                }
                Toast.makeText(this, "Save failed !", Toast.LENGTH_LONG).show();
                return;
            case 1:
                String enginDir2 = EnginUtil.getEnginDir();
                if (SettingUtils.loadSetting(enginDir2)) {
                    Toast.makeText(this, "Load succeed!", Toast.LENGTH_LONG).show();
                    return;
                }
                Toast.makeText(this, "Load failed ! Please ensure has settings file zx_settings.ini at directory " + enginDir2, Toast.LENGTH_LONG).show();
                return;
            case 2:
                int i2 = SharedManager.getInstance().getInt("httpDomain", 0);
                try {
                    str = getPackageManager().getApplicationInfo(getPackageName(), 128).metaData.getInt("HTTP_DOMAIN", 1) == 1 ? " - 正式" : " - 测试";
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                    str = "";
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("设置服务器");
                builder.setSingleChoiceItems(new String[]{"默认配置" + str, "正式服", "测试服", "输入服务器地址"}, i2, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i3) {
                        dialogInterface.dismiss();
                        needRestart = true;
                        if (i3 == 3) {
                            final EditText editText = new EditText(DeveloperOptionsActivity.this);
                            editText.setInputType(16);
                            editText.setText(SharedManager.getInstance().getString("baseUrl", "http://woc.bluebank.com.cn:80/api/"));
                            editText.setInputType(1);
                            new AlertDialog.Builder(DeveloperOptionsActivity.this)
                                    .setTitle("设置服务器基本地址")
                                    .setView(editText)
                                    .setPositiveButton(R.string.ok, (dialogInterface2, i4) -> {
                                        SharedManager.getInstance().setValue("httpDomain", 4);
                                        SharedManager.getInstance().setValue("baseUrl", editText.getText().toString());
                                        SharedManager.getInstance().commit();
                                        App.getContext().showMessage("设置成功！稍后将重启应用");
                                        dialogInterface2.dismiss();
                                    })
                                    .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
                            return;
                        }
                        SharedManager.getInstance().setValue("httpDomain", i3);
                        SharedManager.getInstance().commit();
                        App.getContext().showMessage("设置成功！稍后将重启应用");
                        if (i3 != 2) {
                            return;
                        }
                        final EditText editText2 = new EditText(DeveloperOptionsActivity.this);
                        final String str2 = "" + SharedManager.getInstance().getInt("httpDomain_port", 80);
                        editText2.setHint(str2);
                        editText2.setInputType(2);

                        new AlertDialog.Builder(DeveloperOptionsActivity.this)
                                .setTitle("设置端口")
                                .setView(editText2)
                                .setPositiveButton(R.string.ok, (dialogInterface2, i4) -> {
                                    String obj = editText2.getText().toString();
                                    if (TextUtils.isEmpty(obj)) {
                                        obj = str2;
                                    }
                                    SharedManager.getInstance().setValue("httpDomain_port", Integer.valueOf(obj));
                                    SharedManager.getInstance().commit();
                                })
                                .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
                    }
                });
                builder.create().show();
                return;
            case 3:
                if (EnginUtil.isRecordOpen()) {
                    App.getContext().showMessage("位置记录已开启！请先关闭");
                    return;
                } else if (EnginUtil.isSimulateLocation()) {
                    App.getContext().showMessage("位置模拟已关闭");
                    EnginUtil.setSimulateLocation(false);
                    updateListItem(this.adapter);
                    this.adapter.notifyDataSetChanged();
                    return;
                } else if (EnginUtil.getGpsSimulateFile().exists()) {
                    App.getContext().showMessage("位置模拟已开启，在下一次运动开始生效");
                    EnginUtil.setSimulateLocation(true);
                    updateListItem(this.adapter);
                    this.adapter.notifyDataSetChanged();
                    return;
                } else {
                    App.getContext().showMessage("未找到GpsSimulate.sml文件！");
                    return;
                }
            case 4:
                if (EnginUtil.isSimulateLocation()) {
                    App.getContext().showMessage("位置模拟已开启！无法记录位置");
                    return;
                } else if (EnginUtil.isRecordOpen()) {
                    App.getContext().showMessage("位置记录已关闭");
                    EnginUtil.setRecord(false);
                    updateListItem(this.adapter);
                    this.adapter.notifyDataSetChanged();
                    return;
                } else {
                    App.getContext().showMessage("位置记录已开启，在下一次运动开始生效");
                    EnginUtil.setRecord(true);
                    updateListItem(this.adapter);
                    this.adapter.notifyDataSetChanged();
                    return;
                }
            case 5:
                if (AntPlusUtils.hasAntPlus(getApplicationContext())) {
                    SharedManager.getInstance().setValue(SharedManager.KEY_ANT_PLUS_IS_ENABLED,
                            !SharedManager.getInstance().getBoolean(SharedManager.KEY_ANT_PLUS_IS_ENABLED, false));
                    updateListItem(this.adapter);
                    this.adapter.notifyDataSetChanged();
                    this.needRestart = true;
                    return;
                }
                App.getContext().showMessage("不支持ANT+");
                return;
            case 6:
                boolean z = !SharedManager.getInstance().getBoolean(SharedManager.KEY_DUMP_LOG_AFTER_STOP_SPORT, false);
                SharedManager.getInstance().setValue(SharedManager.KEY_DUMP_LOG_AFTER_STOP_SPORT, z);
                if (z) {
                    toast("开启成功");
                } else {
                    toast("关闭成功");
                }
                this.needRestart = true;
                return;
            case 7:
                if (!EnginUtil.isAPKDebugable(this)) {
                    return;
                }
                SharedManager.getInstance().setValue("debugMode",
                        !SharedManager.getInstance().getBoolean("debugMode", App.getContext().isDebugMode()));
                SharedManager.getInstance().commit();
                this.needRestart = true;
                App.getContext().showMessage("设置成功！稍后将重启应用");
                updateListItem(this.adapter);
                this.adapter.notifyDataSetChanged();
                return;
            case 8:
                if (!EnginUtil.isAPKDebugable(this)) {
                    return;
                }
                SharedManager.getInstance().setValue(SharedManager.KEY_IS_FW_TEST_MODE, !SharedManager.getInstance().isFwTestMode());
                SharedManager.getInstance().commit();
                this.needRestart = true;
                return;
            case 9:
                EnginUtil.startWorkoutFileReCalc(this);
                return;
            case 10:
                if (!EnginUtil.isAPKDebugable(this)) {
                    return;
                }
                final EditText editText = new EditText(this);
                editText.setInputType(2);

                new AlertDialog.Builder(this)
                        .setMessage("Input Workout Server ID:")
                        .setView(editText)
                        .setPositiveButton(R.string.ok, (dialogInterface, i3) -> {
                            String obj = editText.getText().toString();
                            if (obj.matches("[0-9]*")) {
                                EnginUtil.startWorkoutFileReCalc(Long.parseLong(obj), null);
                            } else {
                                App.getContext().showMessage("输入数据不合法！");
                            }
                        })
                        .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
                return;
            case 11:
                final EditText editText2 = new EditText(this);

                new AlertDialog.Builder(this)
                        .setMessage("Input Workout Server ID:")
                        .setView(editText2)
                        .setPositiveButton(R.string.ok, (dialogInterface, i3) -> {
                            String[] split = editText2.getText().toString().split(",");
                            ArrayList arrayList = new ArrayList(split.length);
                            int length = split.length;
                            int i4 = 0;
                            while (true) {
                                if (i4 >= length) {
                                    break;
                                }
                                String str2 = split[i4];
                                if (str2.matches("[0-9]*")) {
                                    Workout byServerId = Workout.getByServerId(Long.parseLong(str2));
                                    if (byServerId == null) {
                                        DeveloperOptionsActivity developerOptionsActivity = DeveloperOptionsActivity.this;
                                        developerOptionsActivity.toast("未找到轨迹[" + str2 + "], 请确认已加载该轨迹");
                                        break;
                                    }
                                    arrayList.add(byServerId);
                                    i4++;
                                } else {
                                    toast("输入数据不合法！");
                                    break;
                                }
                            }

                            if (arrayList.size() == split.length) {
                                Observable.just(arrayList)
                                        .subscribeOn(Schedulers.io())
                                        .flatMap((Func1<ArrayList, Observable<?>>) arrayList1 -> {
                                            WorkoutTest.mergeWorkouts(arrayList1);
                                            return Observable.just(true);
                                        })
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(bool -> DeveloperOptionsActivity.this.toast("merge finished !"));
                            }
                        })
                        .setNegativeButton(R.string.cancel, null)
                        .show();
                return;
            case 12:
                Intent intent = new Intent("bb.lanxing.CYCLING_COMPUTER_FIT_TEST");
                if (intent.resolveActivity(getPackageManager()) == null) {
                    return;
                }
                startActivity(intent);
                return;
            case 13:
                final EditText editText3 = new EditText(this);
                editText3.setInputType(2);

                new AlertDialog.Builder(this)
                        .setMessage("Input Workout Server ID:")
                        .setView(editText3)
                        .setPositiveButton(R.string.ok, (dialogInterface, i3) -> {
                            String obj = editText3.getText().toString();
                            if (obj.matches("[0-9]*")) {
                                long longValue = Long.parseLong(obj);
                                WorkoutOther workoutOther = new WorkoutOther();
                                workoutOther.setServerId(longValue);
                                Intent intent1 = new Intent(DeveloperOptionsActivity.this, SportRecordDetailActivity.class);
                                intent1.putExtra("workoutId", workoutOther.getId());
                                startActivity(intent1);
                                return;
                            }
                            App.getContext().showMessage("输入数据不合法！");
                        })
                        .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
                return;
            case 14:
                final EditText editText4 = new EditText(this);

                new AlertDialog.Builder(this)
                        .setMessage("Input Url:")
                        .setView(editText4)
                        .setPositiveButton(R.string.ok, (dialogInterface, i3) -> {
                            String obj = editText4.getText().toString();
                            if (TextUtils.isEmpty(obj)) {
                                App.getContext().showMessage("Url为毛是空的！");
                            } else {
                                IntentUtils.gotoWebBrowser(DeveloperOptionsActivity.this, obj, null);
                            }
                        })
                        .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
                return;
            case 15:
                final EditText editText5 = new EditText(this);
                new AlertDialog.Builder(this)
                        .setMessage("Input Id:")
                        .setView(editText5)
                        .setPositiveButton(R.string.ok, (dialogInterface, i3) -> {
                            String obj = editText5.getText().toString();
                            if (TextUtils.isEmpty(obj)) {
                                App.getContext().showMessage("ID为毛是空的！");
                                return;
                            }
                            showLoadingDialog((CharSequence) "In progress...", true);
                            routeBookToNavigation(obj).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {
                                }

                                @Override
                                public void onError(Throwable th) {
                                    dismissLoadingDialog();
                                    toast("导出失败");
                                }

                                @Override
                                public void onNext(String str2) {
                                    dismissLoadingDialog();
                                    DeveloperOptionsActivity developerOptionsActivity = DeveloperOptionsActivity.this;
                                    developerOptionsActivity.toastLong("文件已经保存： " + str2);
                                    Uri fromFile = Uri.fromFile(new File(str2).getParentFile());
                                    Intent intent2 = new Intent("android.intent.action.VIEW");
                                    intent2.setDataAndType(fromFile, "resource/folder");
                                    if (intent2.resolveActivityInfo(getPackageManager(), 0) != null) {
                                        startActivity(intent2);
                                    }
                                }
                            });
                        })
                        .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
                return;
            case 16:
                final EditText editText6 = new EditText(this);
                editText6.setInputType(2);

                new AlertDialog.Builder(this)
                        .setMessage("Input Workout Server ID:")
                        .setView(editText6)
                        .setPositiveButton(R.string.ok, (dialogInterface, i3) -> {
                            String obj = editText6.getText().toString();
                            if (obj.matches("[0-9]*")) {
                                EnginUtil.startWorkoutRecord(Long.parseLong(obj), null);
                            } else {
                                App.getContext().showMessage("输入数据不合法！");
                            }
                        })
                        .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
                return;
            case 17:
                startFileChooser(17);
                return;
            default:
                return;
        }
    }

    private void createLocationSimulateFileFromFit(String path) {
        if (path == null || !AppFileUtils.isFileExists(path)) {
            toast("文件不存在");
            return;
        }
        Runnable runnable = () -> dismissLoadingDialog();
        showLoadingDialog("解析文件中...", true);
        EnginUtil.startWorkoutRecordFromFit(path, runnable, runnable);
    }

    private void startFileChooser(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*"); //FILE
        startActivityForResult(intent, requestCode);
    }

    private Observable<RouteBook> requestLushuInfo(long routeBookServerId) {
        RouteBook routeBook = new RouteBook();
        routeBook.setServerId(routeBookServerId);
        return new RouteInfoModelImpl().requestRouteInfo(routeBook);
    }

    public Observable<String> routeBookToNavigation(final String routeBookId) {
        return requestLushuInfo(Long.parseLong(routeBookId)).subscribeOn(Schedulers.io()).flatMap(lushu -> new SprintNavModelImpl().getRoute(lushu, 1024)).map(new Func1<Route, String>() {
            @Override
            public String call(Route route) {
                String json = new GsonBuilder().create().toJson(route);
                String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath("tmp");
                File file = new File(buildExternalDirectoryPath, routeBookId + "_nav.json");
                AppFileUtils.writeFile(json, file.getAbsolutePath());
                return file.getAbsolutePath();
            }
        }).observeOn(AndroidSchedulers.mainThread());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 17 && resultCode == -1) {
            createLocationSimulateFileFromFit(UriUtils.uri2File(data.getData()).getPath());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (this.needRestart) {
            EnginUtil.restartApp(this);
            this.needRestart = false;
        }
    }

    private void bindView(View bindSource) {
        this.toolbar = bindSource.findViewById(R.id.toolbar);
        this.listView = bindSource.findViewById(R.id.engin_function_list);
    }
}
